package com.powerbosframework.web.form;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.powerbosframework.util.StringUtil;
import com.powerbosframework.web.action.GlobalMessage;
import com.powerbosframework.web.action.SupportAction;
import com.powerbosframework.web.form.ActionForm;
import com.powerbosframework.web.form.FormProperty;
import com.powerbosframework.web.util.RequestURI;

/**
 * 文件表单上传类
 * @author youfu.wang
 * @version 1.0
 */
public class MultipartForm extends ActionForm{
	private HttpServletRequest request;
	
	public MultipartForm(HttpServletRequest request) {
		this.request=request;
	}
	private DiskFileItemFactory factory=new DiskFileItemFactory();
	public static int maxSize=5;//最大限制在20M
	public static String saveDir=GlobalMessage.GLOBAL_PATH+File.separator+"temp";
	public static String extensions="bmp,jpg,jpeg,gif";
	private File multipartFile;
	
	public String getExtensions() {
		return extensions;
	}
	public int getMaxSize() {
		return maxSize;
	}
	public String getSaveDir() {
		return saveDir;
	}
	public File getMultipartFile() {
		return multipartFile;
	}
	public void setMultipartFile(File multipartFile) {
		this.multipartFile = multipartFile;
	}

	public void processMultipartForm(SupportAction supportAction) throws InstantiationException, IllegalAccessException{
		FormBeanHelp formBeanHelp=new FormBeanHelp(this.request,supportAction);
		factory.setSizeThreshold(maxSize);
		factory.setRepository(new File(saveDir));
		//创建上传文件对象
		ServletFileUpload upload=new ServletFileUpload(factory);
		//设置上传最大文件
		upload.setSizeMax(maxSize);
		//处理表单上传请求
		List items=null;
		try {
			items=upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}	
		if(items==null) return;
		for(Iterator it=items.iterator();it.hasNext();){
			FileItem item=(FileItem)it.next();
			if(item.isFormField()){
				String name=item.getFieldName();
				String value=item.getString();				
				if(formBeanHelp.isEntityBean(name)){
					isExsitEntityBean=true;
					formBeanHelp.createFormBean(new FormProperty( name,value));
				}else{
					formBeanHelp.setProperty(supportAction, new FormProperty(name,value));
				}				
			}else{
				String name=StringUtil.replaceNull(item.getName());
				if("".equals(name)) continue;
				String fileName=StringUtil.getTimeNum()+name.substring(name.lastIndexOf("."), name.length());	
				String tmpPath="";
				if(saveDir.indexOf("/")!=-1){
					tmpPath=saveDir+File.separator+fileName;	
				}else
					tmpPath=saveDir+File.separator+fileName;
				this.multipartFile=new File(tmpPath);
				if(!this.multipartFile.exists()){
					this.multipartFile.mkdirs();
				}			
				this.multipartFile.delete();				
				//写入文件到临时存储路径	
				if(this.allowTypes(name)){
					FileOutputStream fos=null;
					try {
						fos = new FileOutputStream(this.multipartFile);
						if(item.isInMemory()){//如果上传的文件在内存
							fos.write(item.get());
						}else{
							InputStream in=item.getInputStream();
							byte[] buffer=new byte[1024];
							int len=0;
							while((len=in.read(buffer))>0){
								fos.write(buffer, 0, len);
							}
							in.close();
							fos.close();							
						}		
					} catch (FileNotFoundException e) {			
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					formBeanHelp.setProperty(supportAction,new FormProperty(item.getFieldName(),this.multipartFile));
				}		
			}
		}
	}
	
	
	private boolean allowTypes(String fileName){
		boolean bool=false;
		String[] types=extensions.split(",");
		for(String type:types){					
			if(fileName.toLowerCase().endsWith(type)){
				bool=true;
				break;
			}
		}		
		return bool;
	}
	
}
